package cn.exam.register;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.class.getSimpleName();
    private EditText edtDeviceId;
    private TextView mTvCode;
    private TextView mTvCode2;
    private Toast toast = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {

        edtDeviceId = findViewById(R.id.edt_device_id);
        mTvCode = findViewById(R.id.tv_code);
        mTvCode2 = findViewById(R.id.tv_code2);

        findViewById(R.id.btn_new_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String deviceId = edtDeviceId.getText().toString();
                if (TextUtils.isEmpty(deviceId)) {
                    showToast("请输入设备ID！");
                    return;
                }
                String buffer = MD5Util.MD5(deviceId);
                Log.d(TAG, "buffer: " + buffer);
                mTvCode.setText(buffer);
            }
        });

        findViewById(R.id.btn_verify_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String deviceId = edtDeviceId.getText().toString();
                String code = mTvCode2.getText().toString().toLowerCase();
                String buffer = MD5Util.MD5(deviceId);

                if (TextUtils.equals(code, buffer)) {
                    showToast("验证成功");
                } else {
                    showToast("验证码不合法");
                }
            }
        });

        findViewById(R.id.btn_copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String code = mTvCode.getText().toString();
                if (TextUtils.isEmpty(code)) {
                    showToast("注册码为空");
                    return;
                }
                Tools.copy(getApplicationContext(), code);
                showToast("复制成功");
            }
        });
    }

    private void showToast(String message) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT); // 正常执行
        } else {
            toast.setText(message); // 用于覆盖前面未消失的提示信息
        }
        toast.setGravity(Gravity.CENTER, 0, -30);// 居中显示
        toast.show();
    }
}